//
//  ManagerListVC.swift
//  YueChat
//
//  Created by 1 on 2024/11/1.
//

import UIKit

class ManagerListVC: BaseVC {
    
    var group = DMCCGroup()
    var addGroupArray : Array<Any> = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getManagerList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "管理员"
        setup()
        
    }
    
    @objc func onGroupRefreshChanged () {
        guard let groupInfo = gosnGroup.getGroupInfo(group.groupId) else {
            return
        }
        self.group = groupInfo
        self.tableView.reloadData()
    }
    
    init(group: DMCCGroup = DMCCGroup()) {
        super.init(nibName: nil, bundle: nil)
        self.group = group
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setup () {

        tableView.dataSource = self
        tableView.delegate = self
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
            tableView.sectionFooterHeight = 0
        }
        
        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
    }
    
    func getManagerList () {
//        let list = gosnMember.getMemberList(group.groupId, 0, group.memberCount)
//        list.forEach { member in
//            if member.type == .Admin {
//                dataSource.append(member)
//            }
//        }
        
        dataSource = gosnGroup.getGroupAdmins(group.groupId)
        
        tableView.reloadData()
    }
  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 1 {
            return dataSource.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section == 1) {
            if(self.dataSource.count == 0) {
                return 0.001;
            }
        }
        if(section == 2) {
            return 8;
        }
        return 30;
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 30))
//        view.backgroundColor = UIColor.lightGray
        let label = UILabel(frame: CGRect(x: 16, y: 0, width: 100, height: 30))
        label.font = UIFont.systemFont(ofSize: 14)
        if section == 0 {
            label.text = "群主"
            view.addSubview(label)
        }else if section == 1{
            label.text = "群管理"
            if dataSource.count > 0 {
                view.addSubview(label)
            }
        }
        
       
        
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        if indexPath.section == 2 {
            
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell.contentView.backgroundColor = UIColor.clear
            cell.accessoryType = .disclosureIndicator
            cell.textLabel?.text = "添加管理员"
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        if indexPath.section == 0 {
            let user = gosnUser.getUserInfoDefault(group.owner)
            cell.setUserInfo(userInfo: user)
        }else{
            let member = dataSource[indexPath.row] as! DMCCMember
            let user = gosnUser.getUserInfoDefault(member.memberId)
            cell.setUserInfo(userInfo: user)
        }
//        cell.titleLab.text = name
//        cell.subTitleLab.font = UIFont.systemFont(ofSize: 15)
//        cell.subTitleLab.textColor = UIColor.gray
//        cell.subTitleLab.text = "当前群上限\(group.maxMemberCount)人"
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
//        let array = self.dataSource[indexPath.section] as! Array<String>
//        let name = array[indexPath.row]
        
        if indexPath.section == 2 {
            navigationController?.pushViewController(SetManagerVC(group: group, type: .Manager), animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        
        if indexPath.section == 1 {
            return true
        }
        return false
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action = UITableViewRowAction(style: .default, title: "移出") { [self] (action, indexPath) in
            // 删除操作的处理
            removeUserItem(at: indexPath)
        }
        return [action]
    }
    
    func removeUserItem(at indexPath: IndexPath) {
        guard let member = dataSource[indexPath.row] as? DMCCMember else { return }
        
        
        MHAlert.showLoading()
        
        Task{
            let res = await gosnGroup.delGroupManager(group.groupId, [member.memberId])
                    await MainActor.run {
                        if res{
                            MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
//                            getManagerList()
                            dataSource.remove(at: indexPath.row)
                            tableView.reloadData()
                        }else{
                            MHAlert.showMessage(KLocalizedString("AlertOpearFail"))
                        }
                    }
                }
    }
    
    deinit {
        
    }

}
